package com.ybl.store.backend.interceptor;

import com.ybl.store.common.constant.UserIdentity;
import com.ybl.store.common.context.UserContext;
import com.ybl.store.common.properties.JwtProperties;
import com.ybl.store.common.util.JwtUtil;
import com.ybl.store.backend.dto.UserInfoDTO;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 店员 jwt 令牌拦截器，只有店员即以上级别才能访问
 */
@Component
@RequiredArgsConstructor
public class JwtTokenClerkInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            // 如果不是控制器方法（例如静态资源），则不需要进行 JWT 校验，直接返回 true 放行请求
            return true;
        }

        String token = request.getHeader(jwtProperties.getHeaderKey());
        UserInfoDTO userInfoDTO = JwtUtil.parseJwtToken(jwtProperties.getSecretKey(), token);

        if (!UserIdentity.authentication(userInfoDTO, UserIdentity.clerk)) {
            // 如果 authentication 验证失败，表示 jwt 验证失败，用户无权访问资源
            response.setStatus(401);
            return false;
        }

        UserContext.set(userInfoDTO);
        return true;
    }

    public void postHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler, @Nonnull @Nullable ModelAndView modelAndView) {
        UserContext.remove();
    }
}
